import React, { useState, useEffect, useMemo } from 'react';
import { Select, Spin, Typography, message } from 'antd';
import type { SelectProps } from 'antd/es/select';
import debounce from 'lodash/debounce';
import { getUsers } from '../../services/userService';
import type { User } from '../../types/user';

const { Option } = Select;
const { Text } = Typography;

export interface UserSelectorProps extends Omit<SelectProps<string | string[]>, 'options'> {
  /** 是否支持多選 */
  multiple?: boolean;
  /** 佔位符文本 */
  placeholder?: string;
  /** 選擇後的回調函數 */
  onChange?: (value: string | string[], option: any) => void;
  /** 默認選中的用戶名 */
  defaultValue?: string | string[];
  /** 是否禁用 */
  disabled?: boolean;
  /** 自定義樣式 */
  style?: React.CSSProperties;
  /** 自定義類名 */
  className?: string;
}

/**
 * 用戶選擇器組件
 * 支持單選和多選模式，可以通過關鍵詞搜索用戶
 */
const UserSelector: React.FC<UserSelectorProps> = ({
  multiple = false,
  placeholder = '請選擇用戶',
  onChange,
  defaultValue,
  disabled = false,
  style,
  className,
  ...restProps
}) => {
  // 用戶列表
  const [users, setUsers] = useState<User[]>([]);
  // 加載狀態
  const [loading, setLoading] = useState<boolean>(false);
  // 搜索關鍵詞
  const [searchValue, setSearchValue] = useState<string>('');
  // 錯誤信息
  const [error, setError] = useState<string | null>(null);

  // 防抖搜索函數
  const debouncedFetchUsers = useMemo(() => {
    const loadUsers = async (value: string) => {
      setLoading(true);
      setError(null);
      
      try {
        const response = await getUsers(value);
        
        if (response.Response.Error) {
          setError(response.Response.Error.Message);
          message.error(response.Response.Error.Message);
          setUsers([]);
        } else if (response.Response.Data) {
          setUsers(response.Response.Data);
        } else {
          setUsers([]);
        }
      } catch (err) {
        setError('獲取用戶列表失敗');
        message.error('獲取用戶列表失敗');
        setUsers([]);
      } finally {
        setLoading(false);
      }
    };
    
    return debounce(loadUsers, 500);
  }, []);

  // 初始加載
  useEffect(() => {
    debouncedFetchUsers('');
    
    return () => {
      debouncedFetchUsers.cancel();
    };
  }, [debouncedFetchUsers]);

  // 搜索框內容變化時的處理函數
  const handleSearch = (value: string) => {
    setSearchValue(value);
    debouncedFetchUsers(value);
  };

  // 選擇變化時的處理函數
  const handleChange = (value: string | string[], option: any) => {
    if (onChange) {
      onChange(value, option);
    }
  };

  // 渲染下拉選項
  const options = users.map((user) => (
    <Option key={user.UserName} value={user.UserName} label={user.UserName}>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <span>{user.UserName}</span>
        <span style={{ color: '#999' }}>{user.UserAge}歲</span>
      </div>
    </Option>
  ));

  return (
    <div className={className} style={style}>
      <Select
        showSearch
        mode={multiple ? 'multiple' : undefined}
        placeholder={placeholder}
        defaultActiveFirstOption={false}
        showArrow
        filterOption={false}
        onSearch={handleSearch}
        onChange={handleChange}
        notFoundContent={loading ? <Spin size="small" /> : error ? <Text type="danger">{error}</Text> : '無匹配用戶'}
        defaultValue={defaultValue}
        style={{ width: '100%' }}
        disabled={disabled}
        {...restProps}
      >
        {options}
      </Select>
    </div>
  );
};

export default UserSelector; 